package br.com.projetovendas.persistencia;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;

import br.com.projetovendas.beans.Vendedor;
import br.com.projetovendas.util.HibernateUtil;


public class VendedorDAOImp implements VendedorDAO {
	private Session session = null;
	private Transaction transaction = null;
	
	@Override
	public boolean insereVendedor(Vendedor vendedor) {
		boolean retorno = false;
		try {
			session = HibernateUtil.getSessionfactory().openSession();
			transaction = session.beginTransaction();
			System.out.print("DAO-Email: " + vendedor.getEmail());
			session.persist(vendedor);
			transaction.commit();
			retorno=true;
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		}finally{
			session.close();
		}
		return retorno;
	}
// parei aqui
	@Override
	public boolean alteraVendedor(Vendedor vendedor) {
		boolean retorno = false;
		try {
			session = HibernateUtil.getSessionfactory().openSession();
			transaction = session.beginTransaction();
			session.update(vendedor);
			transaction.commit();
			retorno=true;
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		}finally{
			session.close();
		}
		return retorno;
	}

	@Override
	public boolean excluiVendedor(Vendedor vendedor){
		boolean retorno = false;
		try {
			session = HibernateUtil.getSessionfactory().openSession();
			transaction = session.beginTransaction();
			session.delete(session.get(Vendedor.class, vendedor.getId()));
			transaction.commit();
			retorno=true;
		} catch (HibernateException e) {
			transaction.rollback();
			e.printStackTrace();
		}finally{
			session.close();
		}
		return retorno;
	}

	@Override
	public Vendedor procurarVendedor(Vendedor vendedor) {
		Vendedor v =null;
		try {
			session = HibernateUtil.getSessionfactory().openSession();
			v=(Vendedor) session.get(Vendedor.class,vendedor.getId());
		} catch (HibernateException e) {
			e.printStackTrace();
		}finally{
			session.close();
		}
		return v;
	}

	@Override
	public List<Vendedor> procurarTodosVendedor() {
		List<Vendedor> list = null;
		try {
			session = HibernateUtil.getSessionfactory().openSession();
			list = session.createQuery("select v from Vendedor v ORDER BY id").list();
		} catch (HibernateException e) {
			e.printStackTrace();
		}finally{
			session.close();
		}
		return list;
	}
}
